package com.zuofei.xmpp.fragment;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zuofei.xmpp.R;
import com.zuofei.xmpp.XmppApplication;
import com.zuofei.xmpp.dbhelper.ContactOpenHelper;
import com.zuofei.xmpp.dbhelper.SmsOpenHelper;
import com.zuofei.xmpp.provider.ContactsProvider;
import com.zuofei.xmpp.provider.SmsProvider;
import com.zuofei.xmpp.service.IMService;
import com.zuofei.xmpp.utils.ThreadUtils;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SessionFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SessionFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SessionFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ListView mListView;
    private CursorAdapter mAdapter;

    public SessionFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SessionFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SessionFragment newInstance(String param1, String param2) {
        SessionFragment fragment = new SessionFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private void initView(View view){
        mListView = view.findViewById(R.id.listView);
    }

    private void initListener(){

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initData(){
            setOrUpdateAdapter();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setOrUpdateAdapter() {
        //判断adapter是否存在
        if(mAdapter != null){
            //刷新adapter就行了
            mAdapter.getCursor().requery();
            return;
        }

        ThreadUtils.runInThread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                //得到花名册
                final Cursor c = XmppApplication.getInstance().getContentResolver().query(SmsProvider.URI_SESSION,null,null,new String[]{IMService.mCurAccount,IMService.mCurAccount},null);
                //假如没有数据
                if(c.getCount() <= 0){
                    return;
                }
                //设置adapter,然后显示数据
                ThreadUtils.runInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter = new CursorAdapter(getActivity(),c) {
                            @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                View view = View.inflate(context,R.layout.item_session,null);
                                return view;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {
                                ImageView ivHead = view.findViewById(R.id.head);
                                TextView tvBody = view.findViewById(R.id.body);
                                TextView tvNickName = view.findViewById(R.id.nickname);
                                String body = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.BODY));
                                String account = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SMSTable.SESSION_ACCOUNT));
                                tvBody.setText(body);
                                tvNickName.setText(account);
                            }
                        };
                        mListView.setAdapter(mAdapter);
                    }
                });
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_session, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
